#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：turbo 
@File    ：serializers.py
@Author  ：赵加响
@Date    ：2023/5/23 17:56 
@Desc    ：
"""
from django.db import transaction
from rest_framework import serializers

from apps.rbac.models import Menu
from apps.samples.constants import OPEN
from apps.samples.models import Samples
from bases.serializers import APIModelSerializer


class SamplesSerializer(APIModelSerializer):
    # 数据校验
    require_fields = ('item_no', 'menu', 'valid_date', 'invalid_date')
    non_updatable_fields = ('item_no', 'menu', 'valid_date', 'invalid_date')
    validate_desc = {'table': '开发示例', 'field': 'status', 'status': '生效或者关闭', 'value': ('R', 'C')}
    unique_fields = ('item_no',)

    # 接口新建、修改涉及字段，放宽字段限制，在validate中进行所有的合法性校验，尽量防止在模型层校验
    item_no = serializers.CharField(label='品番', max_length=15, allow_blank=True, allow_null=True, required=False)
    warehouse = serializers.CharField(label='仓库', max_length=15, allow_blank=True, allow_null=True, required=False)
    location = serializers.CharField(label='库位', max_length=15, allow_blank=True, allow_null=True, required=False)
    menu = serializers.PrimaryKeyRelatedField(label='菜单', queryset=Menu.objects.all(), allow_null=True, required=False)
    valid_date = serializers.DateField(label='生效时间', allow_null=True, required=False)
    invalid_date = serializers.DateField(label='失效时间', allow_null=True, required=False)
    note = serializers.CharField(label='备注', max_length=500, allow_null=True, allow_blank=True, required=False)
    quantity = serializers.DecimalField(label='数量', allow_null=True, decimal_places=6, max_digits=18, required=False)
    # 自定义非model serializer字段
    menu_desc = serializers.ReadOnlyField(source='menu.code')
    status_desc = serializers.SerializerMethodField()

    class Meta:
        model = Samples
        fields = '__all__'
        read_only_fields = ('status',)

    def get_status_desc(self, obj):
        return self.field_desc('status', obj.status)

    @transaction.atomic
    def create(self, validated_data):
        validated_data['status'] = OPEN
        return super().create(validated_data)


class SamplesRawQuerySerializer(serializers.Serializer):
    item_no = serializers.CharField()
    warehouse = serializers.CharField()
    location = serializers.CharField()
    valid_date = serializers.DateField()
    invalid_date = serializers.DateField()
    quantity = serializers.DecimalField(decimal_places=6, max_digits=18)

    class Meta:
        fields = '__all__'
